<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" size="mini" @click="showdialog=true">添加角色</el-button>
      <el-table :header-cell-style="{fontSize: '14px', backgroundColor: '#F5F6F8',color:'#909399'}" class="role-table" :data="roleList" border style="width: 100%">
        <el-table-column label="序号" align="center" type="index" width="100" />
        <el-table-column align="center" prop="name" label="角色" width="200">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="state" label="启用" width="200">
          <template v-slot="{row}">
            <span v-if="!row.isEdit">{{ row.state===1?'已启用':row===0?'未启用':'无' }} </span>
            <el-switch v-else v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="description" label="描述">
          <template v-slot="{row}">
            <span v-if="!row.isEdit">{{ row.description }} </span>
            <el-input
              v-else
              v-model="row.editRow.description"
              size="mini"
              type="textarea"
              style="width:300px"
              :autosize="{ minRows:2}"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <template v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="assignPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="editRole(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗?" @onConfirm="delRole(row.id)">
                <template #reference>
                  <!-- @click="delRole(row.id)" -->
                  <el-button size="mini" type="text">删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button size="mini" type="primary" @click="changeEidt(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height:130px" justify="center" align="middle">
        <el-pagination class="pageination" :page-size="pagesize" :current-page="page" size="small" layout="prev, pager, next" :total="total" @current-change="changePage" />
      </el-row>
      <!-- 添加角色弹层组件 -->
      <el-dialog
        :visible.sync="showdialog"
        title="新增角色"
        width="500px"
        @close="cancel"
      >
        <el-form ref="roleForm" label-width="120px" :model="roleData" :rules="rule">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleData.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-switch v-model="roleData.state" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model="roleData.description"
              size="mini"
              type="textarea"
              style="width:300px"
              :autosize="{ minRows:3}"
            />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center" align="midlle">
              <el-col :span="12">
                <el-button size="mini" type="primary" @click="changeRole">确定</el-button>
                <el-button size="mini" @click="cancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分配角色权限弹层 -->
      <el-dialog :visible.sync="showRoleDialog" title="分配权限">
        <el-tree ref="permTree" check-strictly node-key="id" :data="permissionList" default-expand-all show-checkbox :default-checked-keys="permIds" :props="{label:'name'}" />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="changePermissionRole">确认</el-button>
            <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRoleList, postRoleList, deleteRole, putRole, getRoleDetail, putRolePermission } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      roleData: {
        name: '',
        description: '',
        state: 0
      },
      rule: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      showdialog: false,
      roleList: [],
      page: 1,
      pagesize: 5,
      total: 0,
      showRoleDialog: false,
      permissionList: [],
      permIds: [],
      currentId: null
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async changeEidt(row) {
      if (row.editRow.name && row.editRow.description) {
        await putRole({ ...row.editRow, id: row.id })
        // Object.assign(target,source)
        // 疑惑：为什么不直接调用更新列表接口，而是直接给data数据重新赋值
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        this.$message.success('修改角色成功')
      } else {
        this.$message.warning('角色名称或角色描述不能为空')
      }
    },
    changeRole() {
      this.$refs.roleForm.validate(async isOk => {
        if (isOk) {
          await postRoleList(this.roleData)
        }
        this.$message.success('添加角色成功')
        this.getRoleList()
        this.cancel()
      })
    },
    cancel() {
      this.$refs.roleForm.resetFields()
      this.showdialog = false
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page, this.pagesize)
      this.total = total
      this.roleList = rows
      this.roleList.forEach(item => {
        // vue里面添加属性不具有响应式这一特性
        // 通过this.$set()可以解决这一问题
        // item.isEdit = false
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    changePage(page) {
      this.page = page
      this.getRoleList()
    },
    editRole(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async delRole(id) {
      await deleteRole(id)
      this.$message.success('删除角色成功')
      if (this.roleList.length === 1 && this.page > 1) this.page--
      this.getRoleList()
    },
    async assignPermission(id) {
      this.permissionList = transListToTreeData(await getPermissionList(), 0)
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.currentId = id
      this.showRoleDialog = true
    },
    async changePermissionRole() {
      await putRolePermission(this.$refs.permTree.getCheckedKeys(), this.currentId)
      this.$message.success('修改角色权限成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px 15px;
  margin: 10px;
}
.role-table {
  margin-top: 10px;
}
</style>
